<template>
  <a-modal
    title="角色管理"
    :width="760"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading" style="padding:15px 25px;">
      <a-form :form="form" v-bind="formLayout">
        <a-row class="form-row" :gutter="48">
          <div v-for="(v, k) in fields" :key="k">
            <a-col :lg="12" :md="12" :sm="24">
              <a-form-item :label="v.label">
                <template v-if="v.type == 'select'">
                  <a-select
                    v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"
                    @change="v.onChange">
                    <a-select-option :key="sk" v-for="(item,sk) in selectList[v.listName]" :value="v.listValue?item[v.listValue]:item">{{
                      item[v.listLabel]}}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-else-if="v.type == 'textarea'">
                  <a-textarea :auto-size="{ minRows: 5, maxRows: 10 }" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"/>
                </template>
                <template v-else-if="v.type == 'password'">
                  <a-input-password v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" placeholder="請輸入密碼"/>
                </template>
                <template v-else-if="v.type == 'upload'">
                  <a-upload
                    name="file"
                    :showUploadList="false"
                    :customRequest="upload"
                  >
                    <a-button> <a-icon type="upload" /> Click to Upload </a-button>
                  </a-upload>
                  <span v-if="model!==null">{{ model[v.key] }}</span>
                </template>
                <template v-else-if="v.type == 'date'">
                  <a-date-picker valueFormat="yyyy-MM-DD" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" />
                </template>
                <template v-else-if="v.type == 'number'">
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message, type: 'number',transform(value){return Number(value)}}]}]"/>
                </template>
                <template v-else>
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message}]}]"/>
                </template>
              </a-form-item>

              <a-tree
                v-model="checkedKeys"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                @expand="onExpand"
                @select="onSelect"
              />

            </a-col>
          </div>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { _post, _getAuthorityTree } from '@/api/role'
// 表单字段
const fields = [
    { key: 'name', label: '類別名稱', required: true, message: '請輸入貨品類別名稱' }
]
// const treeData = [
//   {
//     title: '0-0',
//     key: '0-0',
//     children: [
//       {
//         title: '0-0-0',
//         key: '0-0-0',
//         children: [
//           { title: '0-0-0-0', key: '0-0-0-0' },
//           { title: '0-0-0-1', key: '0-0-0-1' },
//           { title: '0-0-0-2', key: '0-0-0-2' }
//         ]
//       },
//       {
//         title: '0-0-1',
//         key: '0-0-1',
//         children: [
//           { title: '0-0-1-0', key: '0-0-1-0' },
//           { title: '0-0-1-1', key: '0-0-1-1' },
//           { title: '0-0-1-2', key: '0-0-1-2' }
//         ]
//       },
//       {
//         title: '0-0-2',
//         key: '0-0-2'
//       }
//     ]
//   },
//   {
//     title: '0-1',
//     key: '0-1',
//     children: [
//       { title: '0-1-0-0', key: '0-1-0-0' },
//       { title: '0-1-0-1', key: '0-1-0-1' },
//       { title: '0-1-0-2', key: '0-1-0-2' }
//     ]
//   },
//   {
//     title: '0-2',
//     key: '0-2'
//   }
// ]
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  components: {
  },
  data () {
    this.formLayout = {
    }
    return {
      form: this.$form.createForm(this),
      fields: fields,
      loading: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: []
    }
  },
  watch: {
    checkedKeys (val) {
      console.log('onCheck', val)
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v, i) => this.form.getFieldDecorator(v.key))
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted () {
    _getAuthorityTree().then((ret) => {
      var dataList = ret.data
      for (var i = 0; i < dataList.length; i++) {
        if (dataList[i].parent == null) {
          this.treeData.push({
            title: dataList[i].resourceName,
            key: dataList[i].idAut,
            children: []
          })
        } else {
          // 找出父節點
          for (var j = 0; j < dataList.length; j++) {
            if (dataList[i].parent === dataList[j].resourceName) {
              // 再找出父節點在TreeData的索引
              for (var k = 0; k < this.treeData.length; k++) {
                if (this.treeData[k].title === dataList[j].resourceName) {
                  this.treeData[k].children.push({
                    title: dataList[i].resourceName,
                    key: dataList[i].idAut
                  })
                }
              }
            }
          }
        }
      }
    })
  },
  methods: {
    // handler
    handleSubmit (e) {
      e.preventDefault()
      this.$emit('handleRefresh')
      this.form.validateFields((err, values) => {
        // 檢測是否有選擇權限
        if (this.checkedKeys === '') {
          alert('請選擇權限')
          return
        }
        if (!err) {
          // 新增
          this.loading = true
          if (this.model != null && this.model.idCat != null) {
             // _put(this.model.idCat, values).then((res) => this.handleSuccess(res))
          } else {
            values['idAutList'] = this.checkedKeys
             _post(values).then((res) => this.handleSuccess(res))
          }
        }
      })
    },
    handleSuccess (ret) {
      this.loading = false
      if (ret.code === 0) {
          this.form.resetFields()
          this.$emit('cancel')
          this.$message.info(ret.msg)
      } else {
        this.$message.error('res.msg')
      }
    },
    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck (checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect (selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
    }
  }
}
</script>
